package com.wtf.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Environment;

public class MySensorListener implements SensorEventListener{
    
    //private final SensorManager mSensorManager;
    //private final Sensor mAccelerometer;
	private final double gravity[];
	private final double linear_acceleration[];
	
    String comma = new String(",");
	private PrintWriter mCurrentFile;
	
	
    public MySensorListener() {
      //  getSystemService(Context.SENSOR_SERVICE);
     //   mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        gravity = new double[3];
        linear_acceleration = new double[3];
        
     //   mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        
        
        File path = Environment.getExternalStorageDirectory();
        File file = new File(path, "wtf.txt");
        mCurrentFile = null;
        try {
        	mCurrentFile = new PrintWriter(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
        	e.printStackTrace();
        }
    }
//
	
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
    	 final double alpha = 0.8;

         gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
         gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
         gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

         linear_acceleration[0] = event.values[0] - gravity[0];
         linear_acceleration[1] = event.values[1] - gravity[1];
         linear_acceleration[2] = event.values[2] - gravity[2];
         
         StringBuffer buff = new StringBuffer();
         buff.append(String.valueOf(event.timestamp));
         buff.append(comma);
         buff.append(String.valueOf(event.values[0]));
         buff.append(comma);
         buff.append(String.valueOf(event.values[1]));
         buff.append(comma);
         buff.append(String.valueOf(event.values[2]));
         buff.append(comma);
         buff.append(String.valueOf(gravity[0]));
         buff.append(comma);
         buff.append(String.valueOf(gravity[1]));
         buff.append(comma);
         buff.append(String.valueOf(gravity[2]));
         buff.append(comma);
         buff.append(String.valueOf(linear_acceleration[0]));
         buff.append(comma);
         buff.append(String.valueOf(linear_acceleration[1]));
         buff.append(comma);
         buff.append(String.valueOf(linear_acceleration[2]));
         mCurrentFile.println(buff.toString());
    }
}
